//index.js
const config = getApp().globalData.config
const { ifLogined, isEmptyObject } = require('../../utils/util.js')
let globalData = getApp().globalData
import { postReq } from '../../http/http.js'
//获取应用实例
Page({
  data: {
    indexList: [],
    COUNT: 20
  },
  onShow() {
    this.getEntryByTimeline(true)
  },
  onPullDownRefresh: function () {
    this.getEntryByTimeline(true)
  },
  onReachBottom(){
    this.getEntryByTimeline()
  },
  enterArticleDetail(options){
    let index = options.currentTarget.dataset.index
    let articleInfo = this.data.indexList[index]
    console.log(articleInfo)
    wx.navigateTo({
      url: `/pages/articleDetail/articleDetail?id=${articleInfo.objectId}&type=${articleInfo.type}`
    })
  },
  getEntryByTimeline(reload) {
    wx.showLoading({
      title: '加载中...',
    })
    const auth = ifLogined()
    let timeline = this.data.indexList
    if (isEmptyObject(timeline) || reload) {
      timeline = [{ verifyCreatedAt: '' }]
    }
    let rankIndex = (timeline.slice(-1)[0].verifyCreatedAt) || ''
    wx.request({
      url: `${config.timelineRequestUrl}/get_entry_by_timeline`,
      data: {
        src: 'web',
        uid: auth.uid || '',
        device_id: auth.clientId,
        token: auth.token,
        limit: this.data.COUNT,
        category: 'all',
        recomment: 1,
        before: rankIndex,
      },
      success: res => {
        wx.hideLoading()
        let data = res.data
        if (data.s === 1) {
          wx.hideLoading()
          let list = (data.d && data.d.entrylist) || []
          this.setData({
            indexList: reload ? list : this.data.indexList.concat(list),
          })
        } else {
          wx.showToast({
            title: data.m.toString(),
            icon: 'none',
          })
        }
      },
      fail: () => {
        wx.showToast({
          title: '网路开小差了，请稍后再试',
          icon: 'none',
        })
      },
      complete: () => {
        wx.stopPullDownRefresh()
      },
    })
  },
})
